<?php
namespace app\index\home;
use app\index\home\Common;
use think\Db;
class Api extends Common
{
    // 获取用户信息
    public function getUinfo(){
        $url = config('domain')."/platform/visitor";
        $param['userId'] = 'oKTJA5bsSe6P_OgcA0UGBubhGXU4';
        // echo USER;exit;
        // $param['userId'] = Db::name('userinfo')->where('id',USER)->value('userId');
        // var_dump($param['userId']);exit;
        if(!$param['userId']){
            errMsg('参数错误');
        }
        $param['appId'] = config('appId');
        // $param['userId'] = 'oKTJA5bsSe6P_OgcA0UGBubhGXU4';

        $param['timestamp'] = time();
        $signKey = config('appSecret');
        $sign_param = "appId=".$param['appId']."&sign_key=".$signKey."&timestamp=".$param['timestamp']."&userId=".$param['userId'];
        $param['sign'] = md5($sign_param);
        // print_r($param);exit;
        // trace('param:'.json_encode($param));
        $rs = httpPost($url,json_encode($param));
        // var_dump($rs);exit;
        // 获取用户基本信息
        if($rs){
            $result = json_decode($rs,true);
            // var_dump($result);exit;
            // var_dump($result);exit;
            if($result&&$result['code']==200){
                $userId = $result['data']['userId'];
                $userCheck = Db::name('userinfo')->where('userId',$userId)->value('id');
                // 新用户
                if(!$userCheck){
                    $data['userId'] = $result['data']['userId'];
                    $data['avatarUrl'] = $result['data']['avatarUrl'];
                    $data['gender'] = $result['data']['gender'];
                    $data['phone'] = $result['data']['phone'];
                    $data['createdAt'] = $result['data']['createdAt'];
                    $data['visitorStatus'] = $result['data']['visitorStatus'];
                    if($data['visitorStatus']){
                        $data['visitorStatus'] = implode(',',$data['visitorStatus']);
                    }
                    $data['unionId'] = $result['data']['unionId'];
                    $data['publicStatus'] = $result['data']['publicStatus'];
                    $data['publicOpenId'] = $result['data']['publicOpenId'];
                    $data['ctime'] = time();
                    $newuser_insert = Db::name('userinfo')->insert($data);
                    if($newuser_insert){
                        $return_data['userId'] = $data['userId'];
                        $return_data['avatarUrl'] = $data['avatarUrl'];
                        okMsg($return_data);
                    }
                    else{
                        errMsg('error');
                    }
                }
                else{
                    errMsg('user_exist');
                }
            }
            else{
                errMsg(isset($result["msg"])?$result["msg"]:"接口出错");
            }
            // var_dump($result);
        }
        else{
            errMsg('接口出错!');
        }
    }

     /**
     * @title 获取红包配置
     */
    public function getredbaglist(){
        $url = config('domain')."/platform/redPack/query";
        $param['appId'] = config('appId');
        $param['timestamp'] = time();
        $param['page'] = 1;
        $param['pageSize'] = 100;
        $signKey = config('appSecret');
        $param['sign'] = makeSign($param,$signKey);
        $rs = httpPost($url,json_encode($param));
        // print_r($param);exit;
        // var_dump($rs);exit;
        if($rs){
            $result = json_decode($rs,true);
            if($result&&$result['code']==200){
                var_dump($result['data']['list']);
            }else{
                errMsg(isset($result["msg"])?$result["msg"]:"接口出错");
            }
        }
    }

    // 发放红包
    public function sendRed($userId,$package_id){
        $url = config('domain').'/platform/redPack/send';
        $param['appId'] = config('appId');
        $param['timestamp'] = time();
        $param['userId'] = $userId;
        $param['packConfigId'] = $package_id;
        $signKey = config('appSecret');
        $param['sign'] = makeSign($param,$signKey);
        $rs = httpPost($url,json_encode($param));
        // var_dump($rs);
        if($rs){
            $result = json_decode($rs,true);
            if(!isset($result['code'])){
                errMsg(isset($result["msg"])?$result["msg"]:"接口出错");
            }
            if($result&&$result['code']==200){
                // var_dump($result['data']);
                return true;
            }else{
                // errMsg(isset($result["msg"])?$result["msg"]:"接口出错");
                return false;
            }
        }
        else{
            return false;
        }
    }

    // 查询可发放卡券列表
    public function getCouponList(){
        $url = config('domain')."/platform/prize/list";
        $data = [
            'activityCode'=>config('activityCode')
        ];
        $rs = httpPost($url,json_encode($this->getsign($data)));
        // var_dump($this->getsign($data));exit;
        // var_dump($rs);exit;
        if($rs){
            $result = json_decode($rs,true);
            if($result&&$result['code']==200){
                return $result['data'];
                // var_dump($result['data']);exit;
            }else{
                return false; 
                // errMsg(isset($result["msg"])?$result["msg"]:"接口出错");
            }
        }
        else{
            return false;
        }
    }
    public function getsign($data){
        $params = $data;
        $params["appId"] = config('appId');
        $params["sign_key"] = config('appSecret');
        $timestamp = time();
        $params["timestamp"] =$timestamp;
        $md5string = makePreString($params,config('appSecret'));
        $sign = md5($md5string);

        $data["appId"] = config('appId');
        $data["sign"] = $sign;
        $data["timestamp"] = $timestamp;

        return $data;
    }
    // 点击开始游戏时调用用户剩余游戏次数接口
    public function getPlayRestTime(){
        $user_id = USER;
        if(!$user_id){
            errMsg('必传参数缺失');
        }
        else{
            $rs = Db::name('userinfo')->where('id',$user_id)->value('game_num');
            
            if(!$rs||$rs<0){
                $return_data['rest_num'] = 0;
            }
            else{
                $return_data['rest_num'] = $rs;
            }
            okMsg($return_data);
        }
    }
    // 游戏数据回传接口
    public function getPlayResult(){
        $user_id = USER;

        // 前端数据接收
        $score = input('score/f');
        $play_time = input('play_time/s');
        $red_num = input('red_num/d');
        $gift_num = input('gift_num/d');
        if(!$user_id||!$score||!$play_time){
            errMsg('必传参数缺失');
        }
        else{
            // 用户表新增红包和礼品数
            $user  = Db::name('userinfo')->where('id',$user_id)->field("score,game_num,red_num,gift_num")->find();
            if($user["game_num"]<=0){
                errMsg("你已经没有游戏次数了");
            }
            $data['userId'] = $user_id;
            $data['score'] = $score;
            $data['play_time'] = $play_time;
            $data['red_num'] = $red_num;
            $data['gift_num'] = $gift_num;
            $data['ctime'] = time();
            // 参与记录入库
            $res = Db::name('play_info')->insert($data);
            if($res){
                $update =[
                    "game_num"=>$user["game_num"]-1
                ];
                if($red_num>0){
                    $update["red_num"] = $user["red_num"] + $red_num;
                }
                if($gift_num>0){
                    $update["gift_num"] = $user["gift_num"] + $red_num;
                }
                /*分数查询*/
                if($user["score"]<$score){
                    $update["score"] = $score;
                }
                Db::name('userinfo')->where('id',$user_id)->update($update);
//                // 查询是否超过最高分数
//                $swhere['score'] = array('lt',$score);
//                $swhere['id'] = $user_id;
//                $score_check = Db::name('userinfo')->where($swhere)->value('id');
//                if($score_check){
//                    $score_update = Db::name('userinfo')->where('id',$user_id)->update(array('score'=>$score));
//                }
                okMsg();
            }
            else{
                errMsg('入库失败，请重试');
            }
        }
    }

    // 一键领取红包、优惠券
    public function oneClickCollect(){
        $where['userId'] = USER;
        $play_info = Db::name('play_info')->where($where)->order('ctime desc')->limit(1)->field('id,red_num,gift_num')->find();
        if(!$play_info){
            errMsg('无此记录');
        }
        // 判断该记录是否有进行过红包抽奖或优惠券抽奖
        $red_record = Db::name('red_list')->where('play_id',$play_info['id'])->value('id');
        $gift_record = Db::name('gift_list')->where('play_id',$play_info['id'])->value('id');
        $gift_sum = Db::name('gift_list')->where('uid',USER)->count('id');//用户已有优惠券总数
        if($red_record||$gift_record){
            errMsg('您已参与过此次游戏抽奖，请勿重复操作');
        }
        else{
            // 游戏获得的红包数量大于0
            $return_data['red'] = array();
            $return_data['gift'] = array();
            // 游戏红包数大于0
            if($play_info['red_num']>0){
                $wheres['get_date'] = date('Y-m-d',time());
                $wheres['uid'] = USER;
                // 当天获取红包数量
                $today_red_count = Db::name('red_list')->where($wheres)->count('id');
                if($today_red_count>=2){
                    // 当天已领取2个红包，当天红包无中奖机会
                }
                else{
                    for($i=0;$i<$play_info['red_num'];$i++){
                        $randNum = rand(1,9999);
                        $packet_result = $this->checkPrize($randNum);
                        if($packet_result['is_prize']){
                            // 中奖
                            $rid = $packet_result['prize_id'];
                            unset($packet_result['prize_id']);
                            
                            $del_num = DB::name('red_rate')->where('id',$rid)->setDec('rest_num',1);
                            if($del_num){
                                $return_data['red'][] = $packet_result;
                                $insert_data['play_id'] = $play_info['id'];
                                $insert_data['price'] = $packet_result['price'];
                                $insert_data['ctime'] = time();
                                $insert_data['uid'] = USER;
                                $insert_data['rid'] = $rid;
                                $insert_data['area'] = AREA;
                                $insert_data['get_date'] = date('Y-m-d',time());
                                $user_id = USERID;
                                $red_pack_status = $this->sendRed($user_id,$rid);
                                if($red_pack_status){
                                    $rs = Db::name('red_list')->insert($insert_data);
                                }
                                else{
                                    continue;
                                }
                                // *********************
                                // 此处需要接客户红包接口发放红包
                                // *********************
                                break;//控制单词抽中红包数只能为1个
                            }
                            else{
                                continue;
                            }
                        }
                        else{
                            continue;
                        }
                    }
                    // okMsg($return_data);
                }
            }
            // 获取优惠券数量大于0
            if($play_info['gift_num']>0&&$gift_sum<5){
                $date = date('Y-m-d',time());
                // *******
                //此处对接客户优惠券接口
                //********
                $area = AREA;
                $coupon_area_list = Db::name('coupon_relation')->where('area_code',$area)->column('coupon_code');
                if($coupon_area_list){
                    $length = count($coupon_area_list)-1;
                    $mycoupon = [];
                    for($i=0;$i<$play_info['gift_num'];$i++){
                        $rand_num = rand(0,$length);
                        array_push($mycoupon,$coupon_area_list[$rand_num]);
                    }
                    $mycoupon = array_unique($mycoupon);
                    $send_status = array();
                    $j = 0;
                    foreach($mycoupon as $key=>$value){
                        if($gift_sum>=5){
                            break;
                        }
                        $rs = $this->giftSend($value,$play_info['id'],$gift_sum);
                        if($rs['code']==200){
                            $gift_sum+=1;
                            $return_data['gift'][] = array('name'=>$rs['name'],'date'=>$rs['date']);
                        }
                    }
                    // var_dump($mycoupon);
                }
            }
            okMsg($return_data);
        }
        // var_dump($play_info);
    }

    public function test(){
        $play_info['gift_num'] = 1;
        if($play_info['gift_num']>0){
            $date = date('Y-m-d',time());
            // *******
            //此处对接客户优惠券接口
            //********
            $area = AREA;
            $coupon_area_list = Db::name('coupon_relation')->where('area_code',$area)->column('coupon_code');
            if(!$coupon_area_list){
                // 区域无可发放的优惠券
                errMsg('nodata');
            }
            else{
                $length = count($coupon_area_list)-1;
                $mycoupon = [];
                for($i=0;$i<$play_info['gift_num'];$i++){
                    $rand_num = rand(0,$length);
                    array_push($mycoupon,$coupon_area_list[$rand_num]);
                }
                $mycoupon = array_unique($mycoupon);
                $send_status = array();
                $j = 0;
                foreach($mycoupon as $key=>$value){
                    $rs = $this->giftSend($value,$play_info['id']);
                    if($rs['code']==200){
                        $return_data['gift'][] = array('name'=>$rs['name'],'date'=>$rs['date']);
                    }
                }
                // var_dump($mycoupon);
            }
        }
    }
    // 调用发放卡券接口
    public function giftSend($coupon_code,$play_id){
        $url = config('domain')."/platform/prize/send";
        $transactionNo = time().rand(1,9999);
        $coupon_list = $this->getCouponList();
        $boundActivityCode = '';
        if(!$coupon_list){
            return array('code'=>0);
        }
        else{
            foreach($coupon_list as $key=>$val){
                if($coupon_code==$val['couponCode']){
                    $boundActivityCode = $val['activityCode'];
                    break;
                }
            }
        }
        $data = [
            'activityCode'=>config('activityCode'),
            'boundActivityCode'=>$boundActivityCode,
            'userId'=>USERID,
            'couponCode'=>$coupon_code,
            'transactionNo'=>$transactionNo
        ];
        // echo $boundActivityCode;exit;
        $rs = httpPost($url,json_encode($this->getsign($data)));
        // var_dump($this->getsign($data));exit;
        // var_dump($rs);exit;
        if($rs){
            $result = json_decode($rs,true);
            if($result&&$result['code']==200){
                if($coupon_list){
                    $gift_name = '';
                    $instructions = '';
                    foreach($coupon_list as $k=>$v){
                        if($v['id']==$result['data']['refCouponConfigId']){
                            $gift_name = $v['couponName'];
                            $instructions = $v['instructions'];
                            break;
                        }
                    }
                    $time = time();
                    $date = date('Y-m-d',time());
                    $insert_data = [
                        'uid'=>USER,
                        'gift_name'=>$gift_name,
                        'status'=>0,
                        'ctime'=>$time,
                        'play_id'=>$play_id,
                        'get_date'=>$date,
                        'refCouponConfigId'=>$result['data']['refCouponConfigId'],
                        'refCouponCode'=>$result['data']['refCouponCode'],
                        'transactionNo'=>$result['data']['transactionNo'],
                        'instructions'=>$instructions,
                        'refCouponReceiveId'=>$result['data']['refCouponReceiveId'],
                        'area'=>AREA
                    ];
                    $insert_res = Db::name('gift_list')->insert($insert_data);
                    if($insert_res){
                        return array('code'=>200,'name'=>$gift_name,'date'=>$date);
                    }
                    else{
                        return array('code'=>0);
                    }
                }
                else{
                    return array('code'=>0);
                }
            }else{
                // errMsg(isset($result["msg"])?$result["msg"]:"接口出错");
                return array('code'=>0);
            }
        }
        else{
            return array('code'=>0);
        }
    }
    // 判断是否中奖
    public function checkPrize($randNum){
        // 获取奖品库存大于0的红包列表
        $where[] = ['rest_num','gt',0];
        $red_rate = Db::name('red_rate')->where($where)->order('id asc')->select();
        // var_dump($red_rate);exit;
        $dt['is_prize'] = false;
        $dt['price'] = 0;
        $dt['prize_id'] = 0;
        $dt['date'] = date('Y-m-d',time());
        if(!$red_rate){
            return $dt;
        }
        $rate_limit = 0;
        foreach($red_rate as $key=>$val){
            $rate_limit += $val['rate']*100;
            if($rate_limit>=$randNum){
                return array('is_prize'=>true,'price'=>$val['price'],'prize_id'=>$val['id']);
            }
            else{
                continue;
            }
        }
        return $dt;
    }

    // 获取用户红包列表
    public function getRedList(){
        $where['uid'] = USER;
        $list = Db::name('red_list')->where($where)->order('ctime desc')->field('price,get_date')->select();
        if($list){
            okMsg($list);
        }
        else{
            errMsg('暂无数据');
        }
    }

    // 获取用户优惠券列表
    public function getGiftList(){
        // 通过接口获取用户优惠券列表，更新使用状态
        $url = config('domain')."/platform/user-prize/list";
        $data = [
            'activityCode'=>config('activityCode'),
            'userId'=>USERID
        ];
        $rs = httpPost($url,json_encode($this->getsign($data)));
        // var_dump($this->getsign($data));exit;
        // var_dump($rs);exit;
        if($rs){
            $result = json_decode($rs,true);
            // var_dump($result['data']);exit;
            if($result&&$result['code']==200){
                foreach($result['data'] as $key=>$value){
                    // var_dump($value['transactionNo']);exit;
                    if(isset($value['transactionNo'])){
                        $wheres['transactionNo'] = $value['transactionNo'];
                        $wheres['uid'] = USER;
                        $up_data['status'] = $value['status'];
                        Db::name('gift_list')->where($wheres)->update($up_data);
                    }
                }
                // var_dump($result['data']);exit;
            }
        }
        $where['uid'] = USER;
        $list = Db::name('gift_list')->where($where)->order('ctime desc')->field('gift_name as activityName,status,instructions')->select();
        if($list){
            okMsg($list);
        }
        else{
            errMsg('暂无数据');
        }
    }

    // 获取排行榜
    public function getRanking(){
        $where[] = ['score','gt',0];
        $rs = Db::name('userinfo')->where($where)->order('score desc')->order('ctime asc')->limit(10)->field('nickname,avatarUrl,score')->select();
        if($rs){
            $uinfo = Db::name('userinfo')->where('id',USER)->field('score,nickname,avatarUrl')->find();
            // var_dump($uinfo);exit;
            $rwhere[] = ['score','gt',$uinfo['score']];
            $myrank = Db::name('userinfo')->where($rwhere)->count('id');
            $myrank += 1;
            $user_data['score'] = $uinfo['score'];
            $user_data['nickname'] = $uinfo['nickname'];
            $user_data['rank'] = $myrank;
            $user_data['avatarUrl'] = $uinfo['avatarUrl'];
            $out = [
                'code' => 200,
                'msg' => 'success',
                'data' => $rs,
                'user'=>$user_data
            ];
            exit(json_encode($out, JSON_UNESCAPED_UNICODE));
            
        }
        else{
            errMsg('暂无数据');
        }
    }

    // 用户中奖列表
    public function getPrizeList(){
        $rs = Db::name('red_list')->alias('a')->join('userinfo b','a.uid=b.id')->field('a.price,b.nickname')->orderRand()->group('a.uid')->limit(20)->select();
        // var_dump($rs);exit;
        if($rs){
            okMsg($rs);
        }
        else{
            errMsg('暂无数据');
        }
    }
}
